<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="user-list-container">
    <!-- 搜索区 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名称">
          <el-input v-model="searchForm.userName" placeholder="请输入" clearable @clear="handleSearch" />
        </el-form-item>

        <el-form-item label="用户角色" style="min-width: 180px;">
          <el-select v-model="searchForm.roleName" placeholder="请选择" clearable @change="handleSearch">
            <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleName" />
          </el-select>
        </el-form-item>

        <el-form-item label="用户状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable @change="handleSearch">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>

        <el-button type="primary" @click="addUser"><i class="el-icon-plus"></i>新增用户</el-button>
      </el-form>
    </el-card>

    <!-- 列表区 -->
    <el-card class="list-card">
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="userName" label="用户名称" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="email" label="电子邮箱" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色信息" width="200">
          <template #default="scope">
            <div v-if="scope.row.roleNames && scope.row.roleNames.length > 0">
              <el-tag
                v-for="(roleName, index) in scope.row.roleNames"
                :key="index"
                type="primary"
                style="margin: 2px;"
              >
                {{ roleName }}
              </el-tag>
            </div>
            <el-tag v-else type="info">未分配角色</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="头像">
          <template #default="scope">
            <el-image
              v-if="scope.row.pic"
              :src="scope.row.pic"
              style="width: 40px; height: 40px; border-radius: 50%"
              fit="cover"
            />
            <div v-else style="width: 40px; height: 40px; border-radius: 50%; background: #eee; display: flex; align-items: center; justify-content: center;">
              <i class="el-icon-user"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="pageNum"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next, total"
        />
      </div>
    </el-card>

    <!-- 用户表单弹窗 -->
    <el-dialog
      v-model="formVisible"
      title="用户表单"
      :width="600"
      :close-on-click-modal="false"
    >
      <!-- 传递角色列表给用户表单组件 -->
      <UserForm
        :model-value="currentUser"
        :role-list="roleOptions"
        @save="handleSave"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUsers, deleteUser, getRoles, deleteUserRoleByUserId, getUserRoles } from '@/api/permission'
import UserForm from './UserForm.vue'
import { ElMessage } from 'element-plus'

const userList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(8)
const formVisible = ref(false)
const currentUser = ref({})

const roleOptions = ref([])

// 更新搜索表单，使用 roleName 字段
const searchForm = ref({
  userName: '',
  roleName: '', // 角色名（模糊匹配）
  status: '', // 用户状态
})

// 获取角色列表用于搜索
const fetchRolesForSearch = async () => {
  try {
    const response = await getRoles({ pageSize: 100 })
    const rawRoles = response.data.records

    const uniqueRoles = new Map()
    rawRoles.forEach(role => {
      const roleId = String(role.id) // 统一使用字符串类型
      const roleName = role.roleName || '未知角色'

      if (!uniqueRoles.has(roleId)) {
        uniqueRoles.set(roleId, {
          roleId,
          roleName
        })
      }
    })

    roleOptions.value = Array.from(uniqueRoles.values())
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error(error)
    roleOptions.value = []
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const params = {
      userName: searchForm.value.userName,
      roleName: searchForm.value.roleName,
      status: searchForm.value.status,
      pageNo: pageNum.value,
      pageSize: pageSize.value
    }

    // 处理状态参数类型转换
    if (params.status !== '' && params.status !== null && params.status !== undefined) {
      // 转换为数字
      params.status = Number(params.status);
    }

    // 过滤掉空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    console.log('发送的搜索参数:', params)

    const response = await getUsers(params)
    userList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  }
}

// 页面加载时同时获取用户列表和角色列表
onMounted(() => {
  fetchUsers()
  fetchRolesForSearch()
})

// 分页切换
const handlePageChange = (page) => {
  pageNum.value = page
  fetchUsers()
}

// 新增用户
const addUser = () => {
  currentUser.value = {}
  formVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  try {
    // 获取用户的角色信息
    const userRolesResponse = await getUserRoles(row.id)
    const userRoleIds = userRolesResponse.data.map(role => String(role.id)) // 统一使用字符串类型

    // 将角色ID添加到当前用户对象中
    currentUser.value = {
      ...row,
      roleIds: userRoleIds
    }

    formVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户角色信息失败')
    console.error(error)
    // 即使获取角色信息失败，也允许编辑用户基本信息
    currentUser.value = { ...row }
    formVisible.value = true
  }
}

// 删除用户
const handleDelete = async (id) => {
  try {
    // 先根据用户ID删除用户角色绑定关系
    try {
      await deleteUserRoleByUserId(id)
      console.log('用户角色绑定关系删除成功')
    } catch (roleDeleteError) {
      console.warn('删除用户角色绑定关系时出错:', roleDeleteError)
    }

    // 再删除用户本身
    await deleteUser(id)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error(error)
  }
}

// 保存用户
const handleSave = () => {
  formVisible.value = false
  fetchUsers()
}

// 搜索功能
const handleSearch = () => {
  pageNum.value = 1 // 重置到第一页
  fetchUsers() // 执行搜索
}

// 重置搜索条件
const handleReset = () => {
  searchForm.value.userName = ''
  searchForm.value.roleName = '' // 重置角色名搜索条件
  searchForm.value.status = ''
  pageNum.value = 1
  fetchUsers()
}
</script>

<style scoped>
.list-card {
  background-color: #fff;
}
.user-list-container{
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  width: 100%;
}
.pagination-container {
  margin-top: 15px;
  text-align: right;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
